let def_width = 0;//默认图片宽度
let def_margin = 0;//默认边距
let h_arr = [];//记录每行总高度；
let clounm = 0;
let page = 1;

function init() {
    let window_width = $('#found').width();
    def_width = 270;//默认图片
    // 宽度
    if (window_width < 600) {
        def_width = 180
    }
    if (window_width < 400) {
        def_width = 130
    }
    def_margin = 15;//默认边距
    h_arr = [];//记录每行总高度；
    clounm = Math.floor((window_width + def_margin) / (def_width + def_margin));//计算应该生成几行
    def_width = Math.floor(((window_width + def_margin) / clounm) - def_margin);//动态补充宽度
    for (i = 0; i < clounm; i++) {
        h_arr.push(0)
    }
    render()
}

//计算数组中最小的数字并且返回对应数组坐标
function min(arr) {
    const num = Math.min(...h_arr);
    const index = h_arr.indexOf(num)
    return index;
}

//根据数字计算左偏移位置；
function sum_left(index = 0) {
    return index * def_width + (index * def_margin);
}

//根据宽度和展示宽度计算倍率计算实际高度；
function sum_height(w, h) {
    const rota = w / def_width;
    return parseInt(h / Math.abs(rota));
}

function render() {
    const list = $(".imgli");
    for (const listElement of list) {
        let img = $(listElement);
        let index = min(h_arr);
        const left = sum_left(index);
        let height = parseInt(sum_height(img.attr('width'), img.attr('height')));

        img.css({
            position: 'absolute',
            width: def_width,
            height: height,
            transform: `translateX(${left}px) translateY(${h_arr[index]}px)`,
        })
        h_arr[index] += height + 15;
        $("#found").css({
            height: h_arr[index], opacity: 1
        })
    }
}

init();
window.addEventListener("resize", debounce(init, 100))

/**
 * 分页
 */
function fetchData() {
    $.ajax({
        url: "/found/all/" + page, method: 'get', type: 'json', success: function (list) {
            list = JSON.parse(list)
            let nodeDom = '';
            for (const listKey of list?.imgs) {
                let delbt = `
                                <button class="layui-btn  layui-btn-xs layui-btn-danger" title="删除这张图片"
                                        onclick="del_img('${listKey.id}','${listKey.imgid}','${listKey.path}','${listKey?.thumb_path}')">
                                    <i class="fa fa-trash-o"></i>
                                </button>
                             `
                const str = `
                    <div class="layui-col-lg3 imgli"  id="img${listKey.id}" width="${listKey.width}" height="${listKey.height}">
                    <div class="img_thumb" onmouseover="show_imgcon(${listKey.id})"
                         onmouseout="hide_imgcon(${listKey.id})">
                        <img src="${domainUrl}${listKey.thumb_path}" alt="${listKey.client_name}"
                             layer-src="${domainUrl}${listKey.path}" lay-src="${domainUrl}${listKey.thumb_path}">
                        <div class="imgcon" id="imgcon${listKey.id}">
                            <!-- 图片链接 -->
                            <a href="javascript:;" title="图片链接" class="layui-btn layui-btn-xs layui-btn-normal"
                               onclick="showlink('${domainUrl}${listKey.path}','${domainUrl}${listKey.thumb_path}')"><i
                                        class="fa fa-link"></i></a>
                            <a href="/img/${listKey.imgid}" target="_blank"
                               class="layui-btn layui-btn-xs layui-btn-normal"><i class="fa fa-globe"></i></a>
                            <!-- 用户已登录才显示删除按钮 -->
                            ${list.is_login ? delbt : ''}
                            <!-- 删除按钮end -->
                        </div>
                    </div>
                </div>

                    `
                nodeDom += str
            }
            $("#found").append(nodeDom)
            init();
            console.log(layui)
        }
    })
}

let tm = true;
window.addEventListener("scroll", function (e) {
    let scroll = window.scrollY || document.documentElement.scrollTop || document.body.scrollTop;
    scroll += innerHeight + 100;
    const H = document.documentElement.scrollHeight;
    if (scroll > H) {
        //懒加载
        if (tm) {
            tm = false;//用于截流
            page += 30;
            fetchData();
            setTimeout(_ => {
                tm = true;
            }, 2000)
        }
    }

})

//防抖
function debounce(fn, wait) {
    var timer = null;
    return function () {
        if (timer !== null) {
            clearTimeout(timer);
        }
        timer = setTimeout(fn, wait);
    }
}